<script setup lang="ts">
import { getLotteryActInfo, addLotteryCount } from "@/api/lottery";
import {
  PlusDescriptions,
  RecordType,
  PlusDialogForm,
  type FieldValues,
  type PlusColumn
} from "plus-pro-components";
import "plus-pro-components/es/components/descriptions/style/css";
import "plus-pro-components/es/components/dialog-form/style/css";
import { ref, computed } from "vue";
import { useRoute } from "vue-router";
import { tabMap } from "./list";
import { setUser } from "@/api/user";
import { getInfo } from "@/api/admin";
import { ElMessage } from "element-plus";
import { deviceDetection } from "@pureadmin/utils";
import { isAllEmpty } from "@pureadmin/utils";
const isMobile = deviceDetection();

defineOptions({
  name: "OperateLotteryDetail"
});
import { useMenu } from "@/utils/power";
const tabPowers = ["record", "user_count"];

const power = useMenu([...tabPowers, "receive_prize"]);

const list = computed(() => {
  const dd = tabPowers
    .filter(item => {
      return power.value[item] == true;
    })
    .map(item => tabMap[item]);
  console.log("list", dd, power.value);

  return dd;
});

const {
  groupData,
  idAuth,
  userFlow,
  chargeList,
  withdrawList,
  financeOrder,
  financeEdit,
  financeDelete
} = power.value;

const route = useRoute();
const actId = Number(route.query.id);

const descColumns: PlusColumn[] = [
  {
    label: "抽奖活动ID",
    width: 120,
    prop: "actId",
    valueType: "copy"
  },
  {
    label: "活动名称",
    width: 120,
    prop: "actName",
    valueType: "copy"
  },
  {
    label: "活动图片",
    width: 120,
    prop: "actImg",
    valueType: "img"
  },
  {
    label: "活动开始时间",
    width: 120,
    prop: "startTime",
    valueType: "text"
  },
  {
    label: "活动结束时间",
    width: 120,
    prop: "endTime",
    valueType: "text"
  },
  {
    label: "活动展示时间",
    width: 120,
    prop: "showStartTime",
    valueType: "text"
  },
  {
    label: "活动展示时间",
    width: 120,
    prop: "showEndTime",
    valueType: "text"
  },
  {
    label: "规则权限",
    width: 120,
    prop: "ruleConfig",
    valueType: "text"
  },
  {
    label: "抽奖规则",
    width: 120,
    prop: "ruleText",
    valueType: "text"
  },
  {
    label: "状态",
    width: 120,
    prop: "actStatus",
    formatter: row => {
      return row === 0 ? "未开始" : row === 1 ? "进行中" : "已结束";
    },
    valueType: "text"
  }
];
const info = ref<RecordType>({});

const loadActDetail = () => {
  getLotteryActInfo({ actId })
    .then(res => {
      info.value = res.data;
    })
    .catch(err => {
      console.log(
        "%c[ err ]-111",
        "font-size:13px; background:pink; color:#bf2c9f;",
        err
      );
    });
};
loadActDetail();

const selected = ref(0);

const rules = {};
const formColumns: PlusColumn[] = [
  {
    label: "余额",
    prop: "money",
    valueType: "input"
  },
  {
    label: "收益",
    prop: "score",
    valueType: "input"
  },
  {
    label: "是否扣除优惠点",
    prop: "isWeight",
    valueType: "select",
    options: [
      {
        label: "否",
        value: 0
      },
      {
        label: "是",
        value: 1
      }
    ]
  },
  {
    label: "等级",
    prop: "level",
    valueType: "select",
    options: [
      {
        label: "普通用户",
        value: 0
      },
      {
        label: "VIP1",
        value: 1
      },
      {
        label: "VIP2",
        value: 2
      },
      {
        label: "VIP3",
        value: 3
      },
      {
        label: "VIP4",
        value: 4
      },
      {
        label: "VIP5",
        value: 5
      },
      {
        label: "VIP6",
        value: 6
      },
      {
        label: "VIP7",
        value: 7
      }
    ]
  },
  {
    label: "显示等级",
    prop: "showLevel",
    valueType: "select",
    options: [
      {
        label: "普通用户",
        value: 0
      },
      {
        label: "VIP1",
        value: 1
      },
      {
        label: "VIP2",
        value: 2
      },
      {
        label: "VIP3",
        value: 3
      },
      {
        label: "VIP4",
        value: 4
      },
      {
        label: "VIP5",
        value: 5
      },
      {
        label: "VIP6",
        value: 6
      },
      {
        label: "VIP7",
        value: 7
      }
    ]
  },
  {
    label: "是否合伙人",
    prop: "starrating",
    valueType: "select",
    options: [
      {
        label: "普通用户",
        value: 0
      },
      {
        label: "合伙人",
        value: 1
      }
    ]
  },
  {
    label: "是否固定等级",
    prop: "levelAdmin",
    valueType: "select",
    options: [
      {
        label: "不固定",
        value: "0"
      },
      {
        label: "固定",
        value: "1"
      }
    ]
  },
  {
    label: "用户状态",
    prop: "status",
    valueType: "select",
    options: [
      {
        label: "启用",
        value: "normal"
      },
      {
        label: "禁用",
        value: "hidden"
      }
    ]
  },
  {
    label: "静态释放",
    prop: "jtsfkg",
    valueType: "select",
    options: [
      {
        label: "关闭",
        value: 0
      },
      {
        label: "开启",
        value: 1
      }
    ]
  }
];
const visible = ref(false);
const values = ref({});
const confirmLoading = ref(false);
function addUserCount() {
  const row = info.value;
  console.log(
    "%crow===编辑>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  // values.value = {
  //   userId: row.id,
  //   money: row.money,
  //   score: row.score,
  //   level: row.level,
  //   starrating: row.starrating,
  //   status: row.status,
  //   levelAdmin: row.level_admin,
  //   showLevel: row.show_level,
  //   jtsfkg: row.jtsfkg,
  //   isWeight: 1
  // };
  addValues.value = {
    actId: row.actId,
    userArr: []
  };

  addVisible.value = true;
}

const handleEditSubmit = async value => {
  const updatedValues = { ...values.value };
  console.log("updatedValues", updatedValues);

  confirmLoading.value = true;
  try {
    const res = await setUser(updatedValues);
    visible.value = false;
    confirmLoading.value = false;
    // formRef.value?.formInstance?.resetFields();
    ElMessage.success("编辑成功");
    loadActDetail();
  } catch (error) {
    confirmLoading.value = false;
    console.log(error, "error");
  }
};

const prize_columns: TableColumnList = [
  {
    label: "奖品名称",
    prop: "prizeName"
  },
  {
    label: "奖品图片",
    slot: "prizeImg"
  },
  {
    label: "奖品类型",
    prop: "prizeType"
  },
  {
    label: "剩余库存",
    prop: "remainStock"
  },
  {
    label: "总库存",
    prop: "totalStock"
  },
  {
    label: "排序",
    prop: "sortOrder"
  },
  {
    label: "状态",
    prop: "status",
    formatter: (row: any) => {
      console.log("row.status", row);
      return row.status === 1 ? "正常" : "禁用";
    }
  },
  {
    label: "概率",
    prop: "probability"
  },
  {
    label: "是否奖励",
    prop: "isWin"
  }
];

const formRef = ref();

const addVisible = ref(false);
const addValues = ref<FieldValues>({});
const addFormColumns: PlusColumn[] = [
  {
    label: "查询用户",
    prop: "uId"
  },
  {
    label: "添加次数",
    valueType: "input",
    prop: "totalCount"
  },
  {
    label: "添加信息",
    prop: "addInfos"
  }
];

const loadUserInfo = async () => {
  try {
    const res = await getInfo(addValues.value.account);
    addValues.value.uId = res.data.uId;
  } catch (error) {
    console.log(error, "error");
  }
};

const addInfoToArray = () => {
  if (isAllEmpty(addValues.value.account)) {
    ElMessage.error("请输入账号");
    return;
  }
  if (isAllEmpty(addValues.value.uId)) {
    ElMessage.error("请查询用户");
    return;
  }

  if (isAllEmpty(addValues.value.totalCount)) {
    ElMessage.error("请输入次数");
    return;
  }

  addValues.value.userArr.push({
    uId: addValues.value.uId,
    account: addValues.value.account,
    totalCount: Number(addValues.value.totalCount)
  });

  addValues.value.uId = undefined;
  addValues.value.account = undefined;
  addValues.value.totalCount = undefined;

  console.log("ddd", addValues.value.userArr);

  // addValues.value = {
  //   actId: addValues.value.actId,
  //   userArr: []
  // };
};

const addCountSubmit = async value => {
  console.log("daddValues", addValues.value);
  if (isAllEmpty(addValues.value.userArr)) {
    ElMessage.error("请添加用户");
    return;
  }

  try {
    const res = await addLotteryCount(addValues.value);
    ElMessage.success("添加成功");
    addVisible.value = false;
  } catch (error) {
    console.log(error, "error");
  }
};

const removeTag = item => {
  addValues.value.userArr = addValues.value.userArr.filter(
    item => item.uId !== item.uId
  );
};
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>活动详情</h3>
        </template>
        <template v-if="power.addUserCount || true" #extra>
          <div class="flex flex-row items-end justify-end">
            <el-button type="primary" @click="addUserCount">
              添加用户抽奖次数
            </el-button>
          </div>
        </template>
      </ElPageHeader>
    </template>
    <PlusDescriptions :columns="descColumns" :column="2" :data="info" />
    <PlusDialogForm
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      :form="{ columns: formColumns, rules, labelWidth: 120 }"
      :dialog="{ confirmLoading, width: isMobile ? '80%' : '40%' }"
      title="编辑用户信息"
      @confirm="handleEditSubmit"
    />
    <template #footer>
      <ElTabs v-model="selected">
        <ElTabPane label="奖品列表" :name="0">
          <pure-table
            border
            row-key="prizeId"
            align-whole="center"
            :data="info.prizeList"
            :columns="prize_columns"
          >
            <template #prizeImg="{ row }">
              <el-image
                :src="row.prizeImg"
                fit="fill"
                style="width: 50px; height: 50px"
                :preview-src-list="[row.prizeImg]"
              />
            </template>
          </pure-table>
        </ElTabPane>
        <ElTabPane
          v-for="(item, index) in list"
          :key="index + 1"
          :name="index + 1"
          :label="item.title"
          :lazy="true"
        >
          <component
            :is="item.component"
            v-if="selected == index + 1"
            :actId="actId"
          />
        </ElTabPane>
      </ElTabs>
    </template>

    <PlusDialogForm
      ref="addFormRef"
      v-model:visible="addVisible"
      v-model="addValues"
      draggable
      :form="{ columns: addFormColumns, labelWidth: 120 }"
      :dialog="{ confirmLoading }"
      title="添加用户抽奖次数"
      @confirm="addCountSubmit"
    >
      <template #plus-field-uId>
        <div class="flex flex-row items-center gap-2">
          <el-input
            v-model="addValues.account"
            placeholder="请输入用户手机号"
            style="width: 100%"
          />
          <el-button type="primary" size="default" @click="loadUserInfo">
            查询用户
          </el-button>
          <div class="w-full">
            查询结果为<strong class="text-red-500">{{ addValues.uId }}</strong>
          </div>
        </div>
      </template>
      <template #plus-field-totalCount>
        <div class="flex flex-row items-center gap-2">
          <el-input
            v-model="addValues.totalCount"
            placeholder="请输入添加次数"
            style="width: 100%"
          />
          <el-button type="primary" size="default" @click="addInfoToArray">
            确认添加
          </el-button>
        </div>
      </template>
      <template #plus-field-addInfos>
        <div class="flex gap-2 flex-wrap">
          <el-tag
            v-for="item in addValues.userArr"
            :key="item.uId"
            type="primary"
            closable
            @close="removeTag(item)"
          >
            账户：{{ item.account }} 次数：{{ item.totalCount }}
          </el-tag>
        </div>
      </template>
    </PlusDialogForm>
  </ElCard>
</template>

<style scoped></style>
